package com.atao.service.impl;

import com.atao.constants.SystemConstant;
import com.atao.domain.Result;
import com.atao.domain.entity.ArticleComment;
import com.atao.mapper.ArticleCommentMapper;
import com.atao.service.ArticleCommentService;
import com.atao.utils.WebRequest;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * (ArticleComment)表服务实现类
 *
 * @author makejava
 * @since 2023-03-23 20:14:39
 */
@Service("articleCommentService")
public class ArticleCommentServiceImpl extends ServiceImpl<ArticleCommentMapper, ArticleComment> implements ArticleCommentService {


    /**
     * Emojis -> EmojisCnt
     */
    private List<Long> parsingEmojiStrings(String emojis) {
        List<Long> ans = new ArrayList<>();
        String[] s = emojis.split(" ");
        for (String value : s) {
            ans.add(Long.valueOf(value));
        }
        return ans;
    }
    /**
     * EmojisCnt -> Emojis 存
     */
    private <T> String parsingEmojiCnt(List<T> emojiCnt) {
        StringBuilder sb = new StringBuilder();
        for (T value : emojiCnt) {
            sb.append(value).append(" ");
        }
        sb.deleteCharAt(sb.length() - 1);
        return sb.toString();
    }

    /**
     * 解析所有 存 递归调用
     */
    private List<ArticleComment> parsingEmojiCntAll(List<ArticleComment> comments) {
        if (comments == null) {
            return null;
        }
        for (ArticleComment comment : comments) {
            comment.setEmojis(parsingEmojiCnt(comment.getEmojisCnt()));
            parsingEmojiCntAll(comment.getSubComments());
        }
        return comments;
    }

    /**
     * 获取文章评论
     * @param id 文章id
     * @return 2级评论
     */
    @Override
    public Result getArticleCommentByArticleId(Long id) {
        List<ArticleComment> articleComments = null;
//        String redisKey = SystemConstant.ARTICLE_COMMENT + id;
//        String redisInfo = redisTemplate.opsForValue().get(redisKey);
//        if (redisInfo != null) {
//            articleComments = JSONUtil.toList(redisInfo, ArticleComment.class);
//            return Result.ok(articleComments);
//        }

        LambdaQueryWrapper<ArticleComment> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ArticleComment::getArticleId, id);
        articleComments = list(wrapper);
        //subComments
        Map<Long, List<ArticleComment>> map = new HashMap<>();

        for (ArticleComment articleComment : articleComments) {
            String emojis = articleComment.getEmojis();
            //解析表情数列
            articleComment.setEmojisCnt(parsingEmojiStrings(emojis));
            if (articleComment.getPid() == -1) {
                map.putIfAbsent(articleComment.getId(), new ArrayList<>());
            } else {
                List<ArticleComment> list = map.getOrDefault(articleComment.getPid().longValue(), new ArrayList<ArticleComment>());
                list.add(articleComment);
                map.put(articleComment.getPid().longValue(), list);
            }
        }
        //过滤掉id不在map中的，对每个设置subComments
        articleComments = articleComments.stream()
                .filter(i -> map.containsKey(i.getId()))
                .collect(Collectors.toList());
        articleComments.forEach(i -> i.setSubComments(map.get(i.getId())));

//        redisTemplate.opsForValue().set(redisKey, JSONUtil.toJsonStr(articleComments));

        return Result.ok(articleComments);
    }

    /**
     * 添加文章评论
     * @param articleComment 评论
     * @return 2级评论
     */
    @Override
    public Result addArticleComment(ArticleComment articleComment) {
        articleComment.setDelFlag(0);
        articleComment.setEmojis(SystemConstant.ARTICLE_COMMENT_DEFAULT_EMOJIS);
        articleComment.setLikes(0L);
        if (articleComment.getCreateById() == null) {
            articleComment.setCreateImg(WebRequest.sendGet(SystemConstant.AUTHOR_IMG_API, null));
            articleComment.setCreateBy(WebRequest.sendGet(SystemConstant.VISITOR_RANDOM_NAME_API, 1));
        }
        save(articleComment);
        //解析表情数列
        articleComment.setEmojisCnt(parsingEmojiStrings(SystemConstant.ARTICLE_COMMENT_DEFAULT_EMOJIS));

//        String redisKey = SystemConstant.ARTICLE_COMMENT + articleComment.getArticleId();
//        redisTemplate.delete(redisKey);

        return Result.ok(articleComment);
    }

    /**
     * 更新评论 reaction
     */
    @Override
    public Result updateReaction(Integer id, Integer commentId, Integer like, List<Integer> cnt) {
        UpdateWrapper<ArticleComment> wrapper = new UpdateWrapper<>();
        wrapper.eq(commentId != null, "id", commentId);
        wrapper.eq("article_id", id);
        wrapper.set(like != null, "likes", like);
        if (cnt != null) {
            String s = parsingEmojiCnt(cnt);
            wrapper.set("emojis", s);
        }
        update(wrapper);
        return Result.ok();
    }

}
